package sy.service.impl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import sy.dao.AdDaoI;
import sy.model.Tad;
import sy.pageModel.DataGrid;
import sy.pageModel.PageHelper;
import sy.service.AdServiceI;

import java.util.*;
@Service
public class AdServiceImpl implements AdServiceI {
	@Autowired
	private AdDaoI adDao;
	
	@Override
	public void delete(String id) {
		adDao.delete(adDao.get(Tad.class, id));
	}

	@Override
	public void add(Tad ad) throws Exception {
		Tad u = new Tad();
		u.setImagePath(ad.getImagePath());
		u.setLinkAddress(ad.getLinkAddress());
		u.setId(UUID.randomUUID().toString());
        u.setContent(ad.getContent());
		//u.settime(new Date());
		adDao.save(u);
	}
	@Override
    public void update(Tad tad){
        adDao.update(tad);
    }
	private String orderHql(PageHelper ph) {
		String orderString = "";
		if (ph.getSort() != null && ph.getOrder() != null) {
			orderString = " order by t." + ph.getSort() + " " + ph.getOrder();
		}
		return orderString;
	}
	@Override
	public DataGrid dataGrid(Tad user, PageHelper ph) {
		DataGrid dg = new DataGrid();
		List<Tad> ul = new ArrayList<Tad>();
		Map<String, Object> params = new HashMap<String, Object>();
		String hql = " from Tad t ";
		List<Tad> l = adDao.find(hql + whereHql(user, params) + orderHql(ph), params, ph.getPage(), ph.getRows());
		if (l != null && l.size() > 0) {
			for (Tad t : l) {
				Tad u = new Tad();
				BeanUtils.copyProperties(t, u);
				ul.add(u);
			}
		}
		dg.setRows(ul);
		dg.setTotal(adDao.count("select count(*) " + hql + whereHql(user, params), params));
		return dg;
	}
	private String whereHql(Tad tad, Map<String, Object> params) {
		String hql = "";
		if (tad != null) {
			hql += " where 1=1 ";
			if (tad.getImagePath() != null) {
                hql += " and t.imagePath like :imagePath";
                params.put("imagePath", "%%" + tad.getImagePath() + "%%");
            }
			if (tad.getImagePath() != null) {
				hql += " and t.linkAddress like :linkAddress";
				params.put("linkAddress", "%%" + tad.getLinkAddress() + "%%");
			}
		}
		return hql;
	}

	@Override
	public List<Tad> getads() {
		
		String hql = " from Tad t ";
		List<Tad> l = adDao.find(hql);
		
		return l;
	}
    @Override
    public Tad get(String id){
        String hql = " from Tad t where t.id= '"+id+"'";
        List<Tad> l = adDao.find(hql);
        if(l!=null&&l.size()>0){
            return l.get(0);
        }
        return null;
    }
}
